package top.deepdesigner.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import top.deepdesigner.pojo.DtsCoupon;
import top.deepdesigner.service.DtsCouponService;

import java.util.Date;
import java.util.List;

/**
 * Start up <br/>
 * Created with IntelliJ IDEA. <br/>
 * Project Name: shop_manage <br/>
 * Author: duanruiqing <br/>
 * DateTime: 2022/9/23 星期五 11:08:05 <br/>
 */
@Service
public class DtsCouponServiceImpl extends ServiceImpl<BaseMapper<DtsCoupon>, DtsCoupon> implements DtsCouponService {
  @Override
  public Long getCouponCount() {
    return this.count(new LambdaQueryWrapper<DtsCoupon>().eq(true, DtsCoupon::getDeleted, 0));
  }

  @Override
  public List<DtsCoupon> getCouponList(Integer page, Integer limit, String sort, String order, String name, Integer type, Integer status) {
    QueryWrapper<DtsCoupon> wrapper = new QueryWrapper<>();
    wrapper.eq(type != null, "type", type)
        .eq(status != null, "status", status)
        .eq(true, "deleted", 0)
        .like(!StringUtils.isEmpty(name), "name", name)
        .orderBy(!StringUtils.isEmpty(sort), "asc".equalsIgnoreCase(order), sort);
    return this.page(new Page<>(page, limit), wrapper).getRecords();
  }

  @Override
  public DtsCoupon getCouponById(Integer id) {
    return this.getOne(new LambdaQueryWrapper<DtsCoupon>()
        .eq(DtsCoupon::getId, id)
        .eq(true, DtsCoupon::getDeleted, 0));
  }

  @Override
  @Transactional
  public DtsCoupon createCoupon(DtsCoupon coupon) {
    List<DtsCoupon> list = this.list(new LambdaQueryWrapper<DtsCoupon>()
        .eq(DtsCoupon::getId, coupon.getId())
        .eq(DtsCoupon::getDeleted, 0));

    if (list != null && list.size() == 0) {
      this.save(coupon);
      return coupon;
    }
    return null;
  }

  @Override
  @Transactional
  public DtsCoupon updateCoupon(DtsCoupon coupon) {
    coupon.setUpdateTime(new Date());
    LambdaUpdateWrapper<DtsCoupon> wrapper = new LambdaUpdateWrapper<>();
    wrapper.eq(true, DtsCoupon::getId, coupon.getId());
    this.update(coupon, wrapper);
    return coupon;
  }

  @Override
  @Transactional
  public void deleteCoupon(DtsCoupon coupon) {
    //防止修改过多字段
    DtsCoupon coupon1 = new DtsCoupon();
    coupon1.setUpdateTime(new Date());
    coupon1.setDeleted(true);
    LambdaUpdateWrapper<DtsCoupon> wrapper = new LambdaUpdateWrapper<>();
    wrapper.eq(true, DtsCoupon::getId, coupon.getId());
    this.update(coupon1, wrapper);
  }
}
